package group

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/fx"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"go-admin/base/utils"

	"go-admin/base/internal/svc"
	"go-admin/base/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserAndGroupsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserAndGroupsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserAndGroupsLogic {
	return &UserAndGroupsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserAndGroupsLogic) UserAndGroups(req *types.UsersGroupsReqDTO) (resp *types.UsersGroupsRespDTOS, err error) {
	// todo: add your logic here and delete this line
	users, err := l.svcCtx.UserModel.FindAll(l.ctx)
	if err != nil {
		fmt.Errorf(err.Error())
		return nil, err
	}

	var usersGroupsRespDTOS []types.UsersGroupsRespDTO
	for _, user := range users {
		usersGroupsRespDTOS = append(usersGroupsRespDTOS, types.UsersGroupsRespDTO{
			UserID:       user.Id,
			UserName:     user.UserName.String,
			UserNum:      user.UserNum.String,
			UserNickName: user.NickName.String,
			UserType:     true,
		})
	}

	userGroups, err := l.svcCtx.UserGroupModel.FindByUserIds(l.ctx, []int64{req.UserId})
	if err != nil && err != sqlx.ErrNotFound {
		fmt.Errorf(err.Error())
		return nil, err
	}
	groupIds := utils.Collector[int64](fx.From(func(source chan<- any) {
		for _, userGroup := range userGroups {
			source <- userGroup.GroupId.Int64
		}
	}))
	if len(groupIds) > 0 {
		groups, _ := l.svcCtx.GroupModel.FindByIds(l.ctx, groupIds)

		for _, group := range groups {
			usersGroupsRespDTOS = append(usersGroupsRespDTOS, types.UsersGroupsRespDTO{
				GroupId:       group.Id,
				GroupName:     group.Name.String,
				GroupNickName: group.NickName.String,
				Description:   group.Description.String,
				UserType:      false,
			})
		}
	}
	return &types.UsersGroupsRespDTOS{
		Data: usersGroupsRespDTOS,
		Result: types.Result{
			Code: 200,
		},
	}, nil
}
